package com.cookie.cookiejoke.utils;

import android.content.ComponentName;

import com.cookie.cookiejoke.model.Destination;
import com.cookie.cookiejoke.navigator.FixFragmentNavigator;

import java.util.HashMap;

import androidx.fragment.app.FragmentActivity;
import androidx.navigation.ActivityNavigator;
import androidx.navigation.NavController;
import androidx.navigation.NavGraph;
import androidx.navigation.NavGraphNavigator;
import androidx.navigation.NavigatorProvider;
import androidx.navigation.fragment.FragmentNavigator;

/**
 * 项目名:    CookieJoke
 * 包名:      com.cookie.cookiejoke.utils
 * 文件名:    NavGraphBuilder
 * 创建者:    cookie
 * 创建时间:   2020/2/25 22:58
 * 描述:      TODO
 */

public class NavGraphBuilder {

    public static void build(NavController controller, FragmentActivity activity, int containerId) {
        NavigatorProvider provider = controller.getNavigatorProvider();
        // FragmentNavigator fragmentNavigator = provider.getNavigator(FragmentNavigator.class);
        FixFragmentNavigator fragmentNavigator = new FixFragmentNavigator(activity,
                activity.getSupportFragmentManager(), containerId);
        provider.addNavigator(fragmentNavigator);
        ActivityNavigator activityNavigator = provider.getNavigator(ActivityNavigator.class);

        NavGraph navGraph = new NavGraph(new NavGraphNavigator(provider));

        HashMap<String, Destination> destConfig = AppConfig.getDestConfig();
        for (Destination value : destConfig.values()) {
            if (value.isIsFragment()) {
                FragmentNavigator.Destination destination = fragmentNavigator.createDestination();
                destination.setClassName(value.getClassName());
                destination.setId(value.getId());
                destination.addDeepLink(value.getPageUrl());

                navGraph.addDestination(destination);
            } else {
                ActivityNavigator.Destination destination = activityNavigator.createDestination();
                destination.setId(value.getId());
                destination.addDeepLink(value.getPageUrl());
                destination.setComponentName(new ComponentName(AppGlobals.getApplication()
                        .getPackageName(), value.getClassName()));
                navGraph.addDestination(destination);
            }

            if (value.isAsStarter()) {
                navGraph.setStartDestination(value.getId());
            }
        }

        //给APP页面导航结果图 设置一个默认的展示页的id
        controller.setGraph(navGraph);
    }
}
